import  React from 'react';
import BreadcrumbCustom from '../BreadcrumbCustom';
import { Row,Form,Input ,DatePicker ,Button, message, Col } from 'antd';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import * as Request from '../../Server/SystemManger';
import qs from 'qs';
import moment from 'moment';
import {filter} from '../../common/utils';
import TablePage from "../TablePage";
import * as Constant from '../../common/const';

require('./customer.css');

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const defaultPage = {page:Constant.DEFAULT_PAGE,size:Constant.DEFAULT_PAGE_SIZE};
const format = Constant.FMT_SECOND;

class UserOpertion extends  React.Component{

    constructor(props){
        super(props);
        this.state = ({
            defaultRange:[],
            dataSource:[],
            pagination:{
            },
            loading:true,
            userName:undefined,
            ip:undefined,
        });
    }

    componentWillMount(){
        const now = new Date();
        const start = moment(now,format);
        this.setState({
            defaultRange:[moment(start.format(Constant.FMT_MONTH)+ '-01 00:00:00',format),moment(now,format)]
        });
    }

    componentDidMount() {
        this.initLogPageData();
    }

    componentWillUnmount() {
        this.setState = () => {
            return;
        };
    }
    search = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                delete values.rangeTime;
                this.setState({...values,loading:true});
                this.initLogPageData({page:Constant.DEFAULT_PAGE,size:this.currentPageSize(),...values});
            }
        });
    }

    reset = () => {
        this.setState({
            userName:undefined,
            ip:undefined,
            loading:true
        });
        this.props.form.setFieldsValue({ip:undefined,userName:undefined,rangeTime:this.state.defaultRange});
        this.initLogPageData({page:0,size:this.currentPageSize()});
    }

    initLogPageData = (params = defaultPage) => {
        const rangeTime = this.props.form.getFieldValue('rangeTime');
        params = {...params,start:rangeTime[0].format(format),end:rangeTime[1].format(format)}
        Request.getLogPage(qs.stringify(params,{ filter: filter})).then(res => {
            if(res && Constant.REQUEST_SUCCESS == res.code){
                let data = res.data;
                this.setState({
                    dataSource:data.content,
                    pagination:{...this.state.pagination,total:data.totalSize,current:data.page + 1,pageSize:params.size},
                    loading:false,
                });
            }else{
                res && res.code !== Constant.REQUEST_UNAUTHORIZED && message.error(res.msg);
                this.setState({
                    loading: false
                })
            }
        })
    }
    /* 翻页 */
    handleTableChange = (pagination) => {
        const _this = this;
        const pager = { ..._this.state.pagination };
        pager.current = pagination.current;
        pager.pageSize = pagination.pageSize;
        _this.setState({
            pagination: pager,
            loading:true
        });
        _this.initLogPageData({
            page: pagination.current -1 ,//后台分页默认从第0页开始
            size: pagination.pageSize,
            userName:_this.state.userName,
            ip:_this.state.ip
        });
    }
    disabledDate = (currentDate) => {
        const now = this.state.defaultRange[1];
        return now.format(format)  < currentDate.format(format);
    }
    validatorRangeTime = (rule,value,callback) => {
        if(!value || !value.length){
            callback();
            return;
        }
        const [start,end] = value;
        if(start.month() !== end.month()){
            callback('不允许跨月查询数据');
        }else{
            callback();
        }
    }
    currentPageSize = () => this.state.pagination.pageSize || Constant.DEFAULT_PAGE_SIZE;
    render(){
        const columns =  [
            {
            title:"时间",
            dataIndex:"recordTime",
            width:'20%',
            align:'center',
            },
            {
                title:"用户名",
                dataIndex:"userName",
                width:'20%',
                align:'center',
            },
            {
                title:"登录IP",
                dataIndex:"ip",
                width:'20%',
                align:'center',
            },
            {
                title:"操作内容",
                dataIndex:"operateContent",
                width:'20%',
                align:'center',
            },
            {
                title:"操作结果",
                dataIndex:"result",
                width:'20%',
                align:'center',
                render:(text) => {
                    if(!text){
                        return <span>成功</span>;
                    }else{
                        return <span style={{color:'red'}}>失败</span>;
                    }
                }
            },
        ];
        const {getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 10 },
                md: 9,
                lg: 6,
                xl: 5
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
                md: 15,
                lg: 18,
                xl: 19
            },
        };
        const timeLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 20 },
            },
        };

        return (
            <div>
                <BreadcrumbCustom  first={'用户操作日志'}/>
                <div>
                    <Row>
                        <Form onSubmit={this.search}>
                            <Col span={5}>
                                <FormItem
                                    {...formItemLayout}
                                    label={'用户名:'}
                                >
                                    {getFieldDecorator('userName', {
                                        initialValue: this.state.userName,
                                    })(
                                        <Input maxLength={255} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={5}>
                                <FormItem
                                    {...timeLayout}
                                    label={'IP:'}
                                >
                                    {getFieldDecorator('ip', {
                                        initialValue: this.state.ip,
                                    })(
                                        <Input maxLength={255} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={9}>
                                <FormItem
                                    {...timeLayout}
                                    label={'时 间:'}
                                >
                                    {getFieldDecorator('rangeTime', {
                                        rules: [{
                                            validator: this.validatorRangeTime
                                        }],
                                        initialValue: this.state.defaultRange.length && this.state.defaultRange,
                                    })(
                                        <RangePicker
                                            style={{width: '100%' }}
                                            placeholder={['开始日期', '结束日期']}
                                            format={format}
                                            showTime={{ format: 'HH:mm:ss' }}
                                            allowClear={false}
                                            locale={locale}
                                            disabledDate={this.disabledDate}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                            <Col {...Constant.BUTTONSPAN} style={{ textAlign: 'center'}}>
                                <FormItem >
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                    >查询</Button>
                                    <Button
                                        type="default"
                                        onClick={this.reset}
                                    >重置</Button>
                                </FormItem>
                            </Col>
                        </Form>
                    </Row>
                    {/*<Row>
                        <Button  size={'large'} onClick={this.addRole}>
                            导出文件
                        </Button>
                    </Row>*/}
                    <Row>
                        <TablePage
                            dataSource={this.state.dataSource}
                            columns={columns}
                            loading={this.state.loading}
                            pagination={this.state.pagination}
                            onChange={this.handleTableChange}
                        />
                    </Row>
                </div>
            </div>
        );
    }
}

const UseroperationForm = Form.create()(UserOpertion);
export default UseroperationForm;